﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.Permission.Dtos.Organize;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 机构管理
    /// 组织架构：公司》部门》岗位》用户
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.21 
    /// </summary>
    [Route("api/Permission/[controller]")]
    public class OrganizeController : BaseApiController
    {
        private OrganizeBll organizeBll = new OrganizeBll();

        #region GET
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList(KeywordInput input)
        {
            var data = (await organizeBll.GetList()).FindAll(t => t.Category.Equals("company"));
            if (!string.IsNullOrEmpty(input.keyword))
            {
                data = data.TreeWhere(t => t.FullName.Contains(input.keyword) || t.EnCode.Contains(input.keyword), t => t.Id, t => t.ParentId);
            }
            var treeList = data.MapToList<OrganizeListOutput>();
            return Success(new { list = treeList.ToTree("-1") });
        }

        /// <summary>
        /// 获取下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet("Selector")]
        public async Task<ResponseResult> GetSelector()
        {
            var data = (await organizeBll.GetList()).FindAll(t => t.Category.Equals("company"));
            var treeList = data.MapToList<OrganizeSelectorOutput>();
            return Success(new { list = treeList.ToTree("-1") });
        }

        /// <summary>
        /// 获取树形
        /// </summary>
        /// <returns></returns>
        [HttpGet("Tree")]
        public async Task<ResponseResult> GetTree()
        {
            var data = (await organizeBll.GetList()).FindAll(t => t.Category.Equals("company"));
            var treeList = data.MapToList<OrganizeTreeOutput>();
            return Success(new { list = treeList.ToTree("-1") });
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var entity = await organizeBll.GetInfo(id);
            var output = entity.MapTo<OrganizeInfoOutput>();
            return Success(output);
        }
        #endregion

        #region POST
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] OrganizeCrInput input)
        {
            if (await organizeBll.IsExistByEnCode(input.enCode, null))
            {
                return Error("编码已存在");
            }
            if (await organizeBll.IsExistByFullName(input.fullName, null))
            {
                return Error("名称已存在");
            }
            var entity = input.MapTo<OrganizeEntity>();
            entity.Category = "company";
            entity.PropertyJson = JsonHelper.ToJson(input.propertyJson);
            var isOk = await organizeBll.Create(entity);
            return isOk > 0 ? Success("新建成功") : Error("新建失败");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            if (await organizeBll.AllowDelete(id))
            {
                var entity = await organizeBll.GetInfo(id);
                var isOk = await organizeBll.Delete(entity);
                return isOk > 0 ? Success("删除成功") : Error("删除失败");
            }
            else
            {
                return Error("此记录被关联引用,不允许被删除");
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(string id, [FromBody] OrganizeUpInput input)
        {
            if (input.parentId.Equals(id))
            {
                return Error("上级公司和公司不能是同一个");
            }
            if (await organizeBll.IsExistByEnCode(input.enCode, id))
            {
                return Error("编码已存在");
            }
            if (await organizeBll.IsExistByFullName(input.fullName, id))
            {
                return Error("名称已存在");
            }
            var entity = input.MapTo<OrganizeEntity>();
            entity.PropertyJson = JsonHelper.ToJson(input.propertyJson);
            var isOk = await organizeBll.Update(id, entity);
            return isOk > 0 ? Success("更新成功") : Error("更新失败");
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [HttpPut("{id}/Actions/State")]
        public async Task<ResponseResult> UpdateState(string id)
        {
            var entity = await organizeBll.GetInfo(id);
            entity.EnabledMark = entity.EnabledMark == 1 ? 0 : 1;
            var isOk = await organizeBll.Update(id, entity);
            return isOk > 0 ? Success("更新成功") : Error("更新失败");
        }
        #endregion
    }
}
